﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace ETModel {
    public abstract class ACategory : Object {

        /// <summary>
        /// 配置文件信息,根据不同环境(服务器和客户端)自行存储自行解析的内容
        /// </summary>
        public string ConfigFileInfo;

        public abstract Type ConfigType { get; }
        public abstract ConfigType GetOne<ConfigType>() where ConfigType : class, IConfig;
        public abstract ConfigType[] GetAll<ConfigType>() where ConfigType : class, IConfig;
        public abstract ConfigType TryGet<ConfigType>(long id) where ConfigType : class, IConfig;
    }

    /// <summary>
    /// 管理该所有的配置
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public abstract class ACategory<T> : ACategory where T : IConfig {
        protected Dictionary<long, IConfig> dict;

        public override void BeginInit() {
            this.dict = new Dictionary<long, IConfig>();

            string configStr = ConfigHelper.GetText(ConfigFileInfo, typeof(T).Name);

            foreach (string str in configStr.Split(new[] { "\n" }, StringSplitOptions.None)) {
                try {
                    string str2 = str.Trim();
                    if (str2 == "") {
                        continue;
                    }
                    T t = ConfigHelper.ToObject<T>(str2);
                    this.dict.Add(t.Id, t);
                } catch (Exception e) {
                    throw new Exception($"parser json fail: {str}", e);
                }
            }
        }

        public override Type ConfigType {
            get {
                return typeof(T);
            }
        }

        public override void EndInit() {
        }

        public override ConfigType TryGet<ConfigType>(long id) {
            IConfig t;
            if (!this.dict.TryGetValue(id, out t)) {
                return default;
            }
            return t as ConfigType;
        }

        public override ConfigType[] GetAll<ConfigType>() {
            return this.dict.Values.Select(t => t as ConfigType).ToArray();
        }

        public override ConfigType GetOne<ConfigType>() {
            return this.dict.Values.First() as ConfigType;
        }
    }
}